package com.example.lianxi222.fragment.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.lianxi222.R;
import com.example.lianxi222.adapter.GiftAdapter;
import com.example.lianxi222.databinding.ActivityLiveBinding;
import com.example.lianxi222.utils.GlideUtils;
import com.example.mvvm_base.net.Const;
import com.example.mvvm_base.userbean.FollowEntity;
import com.example.mvvm_base.userbean.GiftEntity;
import com.example.mvvm_base.userbean.Money;
import com.example.mvvm_base.userbean.VideoEntity;
import com.example.mvvm_base.view.BaseView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.Duration;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseView<ActivityLiveBinding,LiveViewModel> {
private VideoEntity.DataBean videoBean;
 List<GiftEntity.DataBean> giftList=new ArrayList<>();
private GiftAdapter giftAdapter;
private GiftEntity.DataBean  giftBean;
public Money myMoney;
private DanmakuContext danmakuContext;

    @Override
    protected void initData() {
     viewDataBind.liveGsyPlayer.setUp(videoBean.getVideopath(),false,"");
     viewDataBind.liveGsyPlayer.startPlayLogic();
     viewModel.followS.observe(this, followEntity -> {
         if(followEntity.getCode()==200){
             ToastUtils.showLong(followEntity.getMessage());
             viewDataBind.liveBtnFollow.setText("已关注");
             viewDataBind.liveBtnFollow.setBackgroundResource(R.drawable.shape_alpha_black);
             videoBean.setGuanzhu(1);

         }else{
             ToastUtils.showLong(followEntity.getMessage());
         }
     });
     viewModel.followF.observe(this, s -> ToastUtils.showLong(s));
     viewModel.unfollowS.observe(this, followEntity -> {
         if(followEntity.getCode()==200){
             ToastUtils.showLong(followEntity.getMessage());
             viewDataBind.liveBtnFollow.setText("关注");
             viewDataBind.liveBtnFollow.setBackgroundResource(R.drawable.shape_red);
             videoBean.setGuanzhu(0);
         }else{
             ToastUtils.showLong(followEntity.getMessage());
         }
     });
     viewModel.unfollowF.observe(this, s -> {
         ToastUtils.showLong(s);
     });
     //礼物
        viewModel.giftS.observe(this, giftEntity -> {
            if(giftEntity.getCode()==200){
                giftList.clear();
                giftList.addAll(giftEntity.getData());
                giftAdapter.notifyDataSetChanged();
            }
        });
        viewModel.giftF.observe(this, s -> ToastUtils.showLong(s));
        viewModel.moneyS.observe(this, new Observer<Money>() {
            @Override
            public void onChanged(Money money) {
               myMoney=money;
               viewDataBind.liveUserMoneyTv.setText("余额："+myMoney.money+"抖币");
            }
        });
        viewModel.moneyF.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initControlView() {
        //礼物发送动画
        viewDataBind.liveGiftSendBtn.setOnClickListener(view -> {
            //判断是否选择礼物或者余额是否获取到
            if(giftBean==null||myMoney==null){
              ToastUtils.showLong("请选择礼物再发送");
              return;
            }
            //查看余额是否充足
            if(myMoney.money<giftBean.getPrice()){
                ToastUtils.showLong("您的余额不足！");
                return;
            }
            //获取点击的礼物钱用余额减去礼物的钱
          float newMoney=myMoney.money-giftBean.getPrice();
            //将减去礼物钱的余额赋值给当前用户再调用m层里的update方法
            myMoney.money=newMoney;
            viewModel.updateMoney(myMoney);

            //创建一个承载的视窗
            ImageView imageView=new ImageView(this);
            //由于不可以直接给宽高所以用当前根部局的类型点参数设置宽高
            ConstraintLayout.LayoutParams params=new ConstraintLayout.LayoutParams(200,200);
            //将宽高给自己创的视窗
            imageView.setLayoutParams(params);
            //将自己的视窗给根部局
            viewDataBind.liveRoot.addView(imageView);
            //加载图片放入自己写的视窗
            Glide.with(this).load(giftBean.getGiftpath()).into(imageView);
            //获取根部局的宽和高
            int currentWidth=viewDataBind.liveRoot.getMeasuredWidth();
            int currentHeight=viewDataBind.liveRoot.getMeasuredHeight();
            //设置动画
            ObjectAnimator alpha = ObjectAnimator.ofFloat(imageView, "Alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.0f);
            ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "Rotation", 0, 1080);
            ObjectAnimator translationX = ObjectAnimator.ofFloat(imageView, "translationX",
                    currentWidth, currentWidth / 2, currentWidth / 3);
            ObjectAnimator translationY = ObjectAnimator.ofFloat(imageView, "translationY", currentHeight, currentHeight / 2, currentHeight / 3);
            //创建一个动画管理者集合
            AnimatorSet animatorSet = new AnimatorSet();
            //设置动画持续时间
            animatorSet.setDuration(2000);
            //设置插值器（先加速后减速）
            animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
            //一起播放
            animatorSet.playTogether(alpha,rotation,translationX,translationY);
            //添加动画的监听事件
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(@NonNull Animator animation, boolean isReverse) {
                    super.onAnimationStart(animation, isReverse);
                    //礼物布局消失
                    viewDataBind.liveGiftLayoutCl.setVisibility(View.GONE);

                    viewDataBind.liveDanmakuView.clear();
                    viewDataBind.liveDanmakuView.removeAllDanmakus(true);
                    //发出礼物弹幕
                    BaseDanmaku baseDanmaku=danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
                    //送出礼物
                    baseDanmaku.text="送出一个"+giftBean.getGiftname();
                    //文字大小
                    baseDanmaku.textSize=30;
                    //文字颜色
                    baseDanmaku.textColor= Color.WHITE;
                    //设置弹幕出现延迟时间
                    baseDanmaku.setTime(1000);
                    //添加到弹幕视窗
                    viewDataBind.liveDanmakuView.addDanmaku(baseDanmaku);
                    viewDataBind.liveDanmakuView.start();
                }
                @Override
                public void onAnimationEnd(@NonNull Animator animation, boolean isReverse) {
                    super.onAnimationEnd(animation, isReverse);
                    //送完礼物后删除礼物的视窗
                    viewDataBind.liveRoot.removeView(imageView);
                }
            });
            //开启动画集合
            animatorSet.start();

        });
        //礼物适配器
        giftAdapter=new GiftAdapter(giftList);
        viewDataBind.liveGiftListRv.setLayoutManager(new GridLayoutManager(this,5));
        viewDataBind.liveGiftListRv.setAdapter(giftAdapter);
        videoBean = (VideoEntity.DataBean) getIntent().getSerializableExtra("videoBean");
        //设置基本信息
        //头像
        Glide.with(this).load(videoBean.getHeadpath()).circleCrop()
                .error(R.drawable.ic_gift)
                .into(viewDataBind.liveUserIconIv);
        //用户名
        viewDataBind.liveUsernameTv.setText(videoBean.getAuthname());
       //设置关注状态
        viewDataBind.liveBtnFollow.setText(videoBean.getGuanzhu()==0?"关注":"已关注");
        viewDataBind.liveBtnFollow.setBackgroundResource(videoBean.getGuanzhu()==0?R.drawable.shape_red:R.drawable.shape_alpha_black);
        viewDataBind.liveBtnFollow.setOnClickListener(view -> {
         if(videoBean.getGuanzhu()==0){
             //关注
             viewModel.follow(videoBean.getAuthname());
         }else{
             //已关注
             viewModel.cancel_follow(videoBean.getAuthname());
         }
        });
        //添加点赞动画图片
        viewDataBind.liveLikeView.addLikeImages(
                R.drawable.ic_favorite_0,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_5,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_0
        );
        viewDataBind.liveLikeIv.setOnClickListener(view -> {
            viewDataBind.liveLikeView.addFavor();
        });
        //初始化弹幕
        initDan();
        //唤醒弹幕输入框
        viewDataBind.liveDanmuIv.setOnClickListener(view -> {
            viewDataBind.liveDanmuLayoutLl.setVisibility(View.VISIBLE);
        });
        //发送弹幕
        viewDataBind.liveDanmuSendIv.setOnClickListener(view -> sendDan());
        //打开礼物
        viewDataBind.liveGiftIv.setOnClickListener(view -> {
            viewDataBind.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            //获取礼物列表
            viewModel.getGift();
            //获取当前用户的余额
            viewModel.getMoney(SPUtils.getInstance().getString(Const.SP_USERNAME));

        });
       //关闭礼物布局
        viewDataBind.liveCloseTv.setOnClickListener(view -> {
            viewDataBind.liveGiftLayoutCl.setVisibility(View.GONE);
        });
        //给左下角赋值（礼物的名称和图片）
        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            //获取点击当前礼物
            giftBean = giftList.get(position);
            //填充图片
            GlideUtils.getInstance().CircleGlide(this,giftBean.getGiftpath(),viewDataBind.liveGiftSelectIv);
            //填充名字
            viewDataBind.liveGiftNameTv.setText(giftBean.getGiftname());
        });




    }

    private void sendDan() {
        //获取弹幕内容
        String content=viewDataBind.liveDanmuInputEt.getText().toString();
        if(TextUtils.isEmpty(content)){
            ToastUtils.showLong("输入不能为空");
            return;
        }
       //清理弹幕
        viewDataBind.liveDanmakuView.clear();
        viewDataBind.liveDanmakuView.removeAllDanmakus(true);
       //创建弹幕
        BaseDanmaku baseDanmaku=danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        baseDanmaku.text=content;
        baseDanmaku.textSize=30;
        baseDanmaku.textColor= Color.WHITE;
        baseDanmaku.setTime(800);
        //添加到显示view里
        viewDataBind.liveDanmakuView.addDanmaku(baseDanmaku);
        //调用弹幕控件的开始
        viewDataBind.liveDanmakuView.start();
   //弹幕开始后发送延时消息让弹幕输入框隐藏
        viewDataBind.liveDanmakuView.postDelayed(() -> {
            //设置输入框为空
         viewDataBind.liveDanmuInputEt.setText("");
         //设置输入布局为不可见
         viewDataBind.liveDanmuLayoutLl.setVisibility(View.GONE);
        },300);



    }

    private void initDan() {
        //是否开启缓存
        viewDataBind.liveDanmakuView.enableDanmakuDrawingCache(false);
        //清空弹幕
        viewDataBind.liveDanmakuView.clear();
        viewDataBind.liveDanmakuView.removeAllDanmakus(true);
        //创建弹幕上下文
        danmakuContext=DanmakuContext.create();
        //准备（初始化）
        viewDataBind.liveDanmakuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        },danmakuContext);


    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    public Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }
}